package com.zhuqi.netty.handler;

import cn.hutool.core.util.ObjectUtil;
import com.zhuqi.domain.ChatMessageDo;
import com.zhuqi.netty.bootstrap.ChatClient;
import com.zhuqi.proto.LoginMessageProto;
import com.zhuqi.service.ChatMessageService;
import com.zhuqi.util.WebsocketUtil;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.websocket.Session;
import java.util.List;

/**
 * <p>登陆处理器</p>
 * @author zhuqi
 * @since 2023/3/10 14:17
 */
@Slf4j
@Component
@ChannelHandler.Sharable
public class LoggingHandler extends SimpleChannelInboundHandler<LoginMessageProto.LoginMessageResponse> {

	@Resource
	private ChatMessageService chatMessageService;

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, LoginMessageProto.LoginMessageResponse msg) {
		boolean flag = msg.getFlag();
		String content = msg.getContent();
		log.info("登陆状态:{} 消息：{}", flag, content);
		Session userSession = WebsocketUtil.getUserSession(msg.getUsername());
		if (msg.getFlag()) {
			ChatClient.logging.set(true);
			List<ChatMessageDo> chatMessageDos = chatMessageService.selectByUserName(msg.getUsername());
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.append("【旧消息 ===== start】");
			int i = 1;
			for (ChatMessageDo chatMessageDo : chatMessageDos) {
				stringBuilder.append("【消息 - ").append(i).append("】").append(chatMessageDo.getFromUserName()).append(" => ")
						.append(chatMessageDo.getToUserName()).append(": ").append(chatMessageDo.getContent());
			}
			stringBuilder.append("【旧消息 ===== end】");
			WebsocketUtil.sendMessage(userSession, stringBuilder.toString());
		}
		webSocketLoggingTagUpdate(msg, flag, userSession);
	}

	/**
	 * 修改用户登陆标识
	 * @param msg 消息
	 * @param flag 标识
	 */
	private static void webSocketLoggingTagUpdate(LoginMessageProto.LoginMessageResponse msg, boolean flag,
			Session userSession) {
		if (ObjectUtil.isNotEmpty(userSession)) {
			if (flag) {
				WebsocketUtil.updateLoggingStatus(userSession, Boolean.TRUE);
				WebsocketUtil.sendMessage(userSession, "登陆成功！！");
			} else {
				WebsocketUtil.updateLoggingStatus(userSession, Boolean.FALSE);
				WebsocketUtil.sendMessage(userSession, msg.getContent());
			}
		} else {
			log.info("登陆用户 websocket 为空");
		}
	}
}
